<template>
  <!--登录表单组件-->
  <div class="login-form">
    <Login @on-submit="adminLogin" v-preventReClick>
      <UserName name="username" :rules="formRules.usernameRule"/>
      <Password name="login_password" :rules="formRules.passwordRule"/>
      <Captcha class="login-captcha"
               name="captcha"
               :count-down="0"
               @on-get-captcha="handleGetCaptcha">
        <template #text>
          <img :src="formRules.captchaSrc">
        </template>
      </Captcha>
      <Submit/>
    </Login>
  </div>
</template>

<script setup>
import Md5 from 'js-md5';
import {AdminService} from "@/api/admin";
import {getCurrentInstance, onMounted, reactive} from "vue";
import {setStore} from "@/api/utils";
import {CommonServices} from "@/api/common";
import config from '@/config/global.config';


const {proxy} = getCurrentInstance();

const formRules = reactive({
  usernameRule: [
    {
      required: true, message: '用户名不能为空!', trigger: ['blur', 'change'],
    },
    {
      type: 'string',
      pattern: /^[a-zA-Z0-9-]{6,10}$/,
      message: '用户名只能为6至10位且字母、数字!',
      trigger: ['blur', 'change']
    }
  ],
  passwordRule: [
    {
      required: true, message: '密码不能为空', trigger: ['blur', 'change']
    }, {
      type: 'string',
      pattern: /^[a-zA-Z0-9_-]{4,16}$/,
      message: '密码只能是6至10位且包含字母、数字、下划线和破折号!',
      trigger: ['blur', 'change']
    }
  ],
  captchaSrc: config.captchaSrc
})

const adminLogin = async (valid, {username, login_password, captcha}) => {
  const {data} = await AdminService.AdminLogin({
    username: username,
    login_password: Md5(login_password),
    captcha: captcha
  })
  console.log(valid)
  console.log(data)
  if (data.code === 200) {
    proxy.$Message.success({
      content: '登录成功',
      duration: 1.5,
      closable: true,
      onClose: async () => {
        console.log(data)
        setStore('token', data.data.token);
        setStore('user_name', data.data.username)
        await CommonServices.GetAccountAuths();
        proxy.$router.push('/dashboard')
      }
    });
  } else {
    proxy.$Message.warning({
      content: data.data,
      duration: 1.5,
      closable: true,
    })
  }

  handleGetCaptcha();
  console.log(data)
}

// 获取验证码地址
const handleGetCaptcha = () => {
  formRules.captchaSrc = config.captchaSrc + '?id=' + Math.random();
}

</script>

<style scoped lang="less">
@import "./login-form.less";
</style>
